//
//  AddressViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/6/24.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "AddressViewController.h"
#import "AddressCell.h"
#import "NewOrEitdViewController.h"
#import "IGSearchAddressApi.h"
#import "IGAddAddressApi.h"
#import "IGCommonApi.h"

#define AUTOLAYOUTSIZE(size) ((size) * (KSCREENWIDTH / 375))

@interface AddressViewController () <UITableViewDataSource, UITableViewDelegate> {
    void(^blocks)(IGAddressItem *info);
}

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, strong) NSMutableArray *addressArr;
@property(nonatomic,strong)IGSearchAddressApi *searchAddressApi;
@property(nonatomic,strong)IGCommonApi *commonApi;
@property(nonatomic,strong)IGAddAddressApi *addUpDateApi;
@property(nonatomic,strong)IGSearchAddressModel *searchModel;
@property(nonatomic,copy)NSString *AddressId;
@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *tel;
@property(nonatomic,copy)NSString *home;
@property(nonatomic,copy)NSString *address;


@end

@implementation AddressViewController
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"收货地址管理";
    self.title = NSLocalizedString(@"Recipient Address Management", nil);
    self.table.estimatedRowHeight = 130;
    self.commonApi=[[IGCommonApi alloc] init];
    
    self.table.backgroundColor = [UIColor c2Color];
    self.table.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.table.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 44, 0);
    
    UIButton *addNew = [UIButton buttonWithType:UIButtonTypeCustom];
    addNew.frame = CGRectMake(0, 0, KSCREENWIDTH, 44);
    addNew.backgroundColor = [UIColor appColor];
//    [addNew setTitle:@"添加新地址" forState:UIControlStateNormal];
    [addNew setTitle:NSLocalizedString(@"Add New Address", nil) forState:UIControlStateNormal];
    [addNew setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addNew addTarget:self action:@selector(addNewAddress:) forControlEvents:UIControlEventTouchUpInside];
    addNew.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:addNew];
    addNew.bottom = KSCREENHEIGHT;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self  loadData];
}

#pragma mark -懒加载
- (NSMutableArray *)addressArr {
    if (!_addressArr) {
        _addressArr = [NSMutableArray array];
    }
    return _addressArr;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.addressArr.count?:0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addreCell"];
    if (cell == nil) {
       cell = [[AddressCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"addreCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    IGAddressItem *addressItem = self.addressArr[indexPath.section];
    
    __weak typeof(self) weakSelf = self;
    __weak typeof(addressItem) weakAddressItem = addressItem;
    //设置默认地址
    [cell deftAction:^(IGAddressItem *info) {
        weakSelf.commonApi.addressId = weakAddressItem.aid;
        weakSelf.commonApi.apiType = IGiGalleryApiTypeSetDeafultAddress;
        [weakSelf.commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                
                for (IGAddressItem *address in weakSelf.addressArr) {
                    if ([address.home isEqualToString:@"1"]) {
                        address.home = @"0";
                        break;
                    }
                }
                addressItem.home = @"1";
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.table reloadData];
                });
            }
        }];

    }];
    
    //编辑地址
    [cell editAction:^(IGAddressItem *info) {
        NewOrEitdViewController *vc = [[NewOrEitdViewController alloc] init];
        vc.addressItem = weakAddressItem;
        vc.isEdit = YES;
        BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:NULL];
    }];
    
    //删除地址
    [cell delAction:^(IGAddressItem  *info) {
        weakSelf.commonApi.addressId = weakAddressItem.aid;
        weakSelf.commonApi.apiType = IGiGalleryApiTypeDelAdress;
        [weakSelf.commonApi startWithDecodeClass:[IGCommonResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                [weakSelf.addressArr removeObjectAtIndex:indexPath.section];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.table reloadData];
                });
            }
        }];
    }];
    
    cell.data = addressItem;
    [cell setNeedsLayout];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    IGAddressItem *addressItem = self.addressArr[indexPath.section];
    if (blocks)
    {
        blocks(addressItem);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didSelRow:(void(^)(IGAddressItem *info))block {
    blocks = [block copy];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return AUTOLAYOUTSIZE(100);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 15;
}


- (void)addNewAddress:(UIButton *)btn {
    NewOrEitdViewController *vc = [[NewOrEitdViewController alloc] init];
    
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:NULL];
}

- (void)loadData{
     __weak typeof(self) weakSelf = self;
    self.searchAddressApi=[[IGSearchAddressApi alloc]init];
    [self.searchAddressApi startWithDecodeClass:[IGSearchAddressResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGSearchAddressResp *resp = responseObject;
            IGSearchAddressModel *model = resp.data;
            weakSelf.addressArr = [NSMutableArray arrayWithArray:model.addressList];
            [weakSelf.table reloadData];
        }else{
        
        }
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
